# -*- coding: utf-8 -*-
import sys
import cv2.cv as cv

ptTopLeft = (20, 20)
ptBottomRight = (220, 220)
pInitImage = None
pCurImage = None
nFrameCount = 0

cv.NamedWindow('Source', 1)
cv.NamedWindow('Init', 1)
cv.NamedWindow('Output', 1)

cv.MoveWindow('Source', 10, 10)
cv.MoveWindow('Init', 700, 10)
cv.MoveWindow('Output', 700, 280)

pCapture = cv.CaptureFromCAM(0)
if not pCapture:
    print 'Can not open camera.'
    sys.exit(0)

while 1:
    pFrame = cv.QueryFrame(pCapture)
    if not pFrame:
        print 'Can not open frame.'
        sys.exit(0)
    nFrameCount = nFrameCount + 1

    #print nFrameCount

#    if nFrameCount == 1:

    cv.Rectangle(pFrame, ptTopLeft, ptBottomRight, 0xFFFFFF, 1, cv.CV_AA, 0)
    cv.ShowImage('Source', pFrame)

    if cv.WaitKey(1) == 27:
        break
    if cv.WaitKey(1) == 105:
        pInitImage = cv.CreateImage((200, 200), 8, 3)
        cv.SetImageROI(pFrame, (20, 20, 200, 200))
        cv.Copy(pFrame, pInitImage)
        cv.ResetImageROI(pFrame)
        cv.ShowImage('Init', pInitImage)
        print 'Init image.'
    if cv.WaitKey(1) == 100:
        if pInitImage != None:
            cv.ShowImage('Output', pInitImage)
